<template>
  <div class="bigbox">
    <!-- 表头盒子 -->
    <div class="leftbox">
      <!-- 树节点过滤 -->
      <div>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          v-model="filterText"
        >
        </el-input>
      </div>
      <!-- 树组件 -->
      <div style="margin-top: 15px">
        <el-tree
          ref="tree"
          :props="props"
          :highlight-current="true"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode"
          :default-checked-keys="[0]"
          :load="loadNode"
          node-key="domainId"
          lazy
        >
          <span slot-scope="{ node }" class="slot-t-node">
            <template>
              <!-- <img
                class="node-img"
                v-if="data.bizOrgType == '03' || data.bizOrgType == '30'"
                src="../../assets/node0.png"
              />
              <img
                class="node-img"
                v-if="data.bizOrgType == '04' || data.bizOrgType == '40'"
                src="../../assets/node1.png"
              /> -->
              <span :style="{ 'font-size': '14px' }">{{ node.label }}</span>
            </template>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="mainbox">
      <div class="top">
        <div class="search">
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="inputValue"
          >
          </el-input>
        </div>
        <div class="towBtn">
          <button @click="chongzhi" class="button">重置</button>
          <button @click="chaxun" class="button chaxun">查询</button>
        </div>
      </div>
      <div class="bodybox">
        <!-- 新增按钮 -->
        <!-- 循环图片盒子 -->
        <div class="table">
          <div class="titlebox">
            <div class="text"></div>
            <div
              class="right"
              :style="{ alignItems: 'center', lineHeight: '32.5px' }"
            >
              <button
                type="primary"
                size="small"
                class="bewdao daochu"
                @click="submit('add')"
              >
                <i style="margin-left: 0px" class="el-icon-plus"></i>新增
              </button>
              <el-tooltip
                class="item"
                effect="dark"
                content="刷新"
                placement="top"
              >
                <span
                  @click="shuaxin"
                  :style="{ cursor: 'pointer', fontSize: '20px' }"
                  ><i class="el-icon-refresh-right"></i
                ></span>
              </el-tooltip>
              <el-dropdown trigger="click" @command="command">
                <span class="el-dropdown-link">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="密度"
                    placement="top"
                  >
                    <span :style="{ cursor: 'pointer', fontSize: '20px' }"
                      ><i class="el-icon-d-caret"></i
                    ></span>
                  </el-tooltip>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item class="dropdown-list" command="默认"
                    >默认</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="中等"
                    >中等</el-dropdown-item
                  >
                  <el-dropdown-item class="dropdown-list" command="紧凑"
                    >紧凑</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center',
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <!-- <el-table-column
              align="center"
              type="index"
              width="50"
              label="序号"
            >
            </el-table-column> -->
            <el-table-column
              align="left"
              prop="rootDomainCode"
              label="所属主域"
            >
            </el-table-column>
            <el-table-column align="left" prop="domainCode" label="域编码">
            </el-table-column>
            <el-table-column align="left" prop="domainName" label="域名称">
            </el-table-column>
            <el-table-column align="left" prop="domainExplain" label="域说明">
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: rgb(64, 149, 229);
                      margin-right: 20px;
                      cursor: pointer;
                    "
                    class="el-icon-edit"
                    @click="edit(scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: red;
                      cursor: pointer;
                      margin-right: 20px;
                    "
                    class="el-icon-delete"
                    @click="del(scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="上移"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: rgb(64, 149, 229);
                      cursor: pointer;
                      margin-right: 20px;
                    "
                    class="el-icon-upload2"
                    @click="move('up', scope.row)"
                  ></i
                ></el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="下移"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 14px;
                      color: rgb(64, 149, 229);
                      cursor: pointer;
                    "
                    class="el-icon-download"
                    @click="move('down', scope.row)"
                  ></i
                ></el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-pagination
            background
            class="pagination"
            layout="prev, pager, next"
            :current-page.sync="pageobj._pageNo"
            @current-change="chaxun"
            :total="total"
          >
          </el-pagination> -->
        </div>
        <!-- 新增/修改弹框 -->
        <div>
          <el-dialog
            :show-close="true"
            :visible.sync="dialogVisible"
            width="500px"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            :before-close="diaClose"
            :center="true"
          >
            <div class="dialog">
              <!-- 企业下拉 -->
              <el-form
                ref="dialogForm"
                :rules="rules"
                :model="dialogForm"
                label-width="110px"
              >
                <el-form-item
                  v-if="domainType === '0' || domainType === '1'"
                  label="上级域"
                  prop="parentId"
                >
                  <el-input v-model="dialogForm.parentId" disabled></el-input>
                </el-form-item>
                <el-form-item label="域编码" prop="domainCode">
                  <el-input
                    v-model="dialogForm.domainCode"
                    :disabled="isedit === 'edit'"
                  ></el-input>
                </el-form-item>
                <el-form-item label="域名称" prop="domainName">
                  <el-input v-model="dialogForm.domainName"></el-input>
                </el-form-item>
                <el-form-item label="域说明" prop="domainExplain">
                  <el-input
                    v-model="dialogForm.domainExplain"
                    type="textarea"
                    :rows="4"
                    resize="none"
                  ></el-input>
                </el-form-item>
              </el-form>
              <!-- 弹窗内容 -->
            </div>
            <div style="margin-top: 10px; text-align: center">
              <span slot="footer" class="dialog-footer">
                <el-button @click="diaClose">取 消</el-button>
                <el-button type="primary" @click="add">确 定</el-button>
              </span>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getRootDomainListApi,
  getChildDomainListApi,
  addRootDomainApi,
  // delDomainApi,
  addChildDomainApi,
  getDomainDataApi,
  editDomainApi,
  upDomainApi,
  downDomainApi,
  delDomainApi
} from '@/api/Device-all/Device-domain'
// import { saveAs } from 'file-saver'
export default {
  name: 'DeviceDomain',
  data () {
    return {
      // list: [
      //   {
      //     domainName: '模型定义',
      //     domainId: 0,
      //     domainType: 'Root',
      //     parentId: null
      //   }
      // ],
      filterText: '',
      inputValue: '',
      domainId: '',
      domainType: '',
      parentId: '',
      node: null,
      diaTime: '',
      timeType: true,
      tableData: [],
      loading: false,
      iissize: 'medium',
      dialogForm: {},
      rules: {
        parentId: [
          { required: true, message: '请输入上级域代码', trigger: 'blur' }
        ],
        domainCode: [
          { required: true, message: '请输入域编码', trigger: 'blur' }
        ],
        domainName: [
          { required: true, message: '请输入域名称', trigger: 'blur' }
        ]
      },
      deflist: [],
      props: {
        label: 'domainName'
      },
      dialogVisible: false,
      isedit: 'add'
      // pageobj: {
      //   _pageNo: 0,
      //   _pageSize: 15,
      // },
      // total: 0,
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  async mounted () {
    await this.getRootDomainList()
    this.refreshNode(100)
    this.$refs.tree.setCurrentKey(100)
    this.domainType = this.tableData[0].domainType
    this.domainId = this.tableData[0].domainId
    this.getChildDomainList(this.domainId)
  },
  methods: {
    async getRootDomainList () {
      this.loading = true
      const res = await getRootDomainListApi()
      this.deflist = res.data.list
      this.tableData = res.data.list
      this.loading = false
    },
    async getChildDomainList (id) {
      this.loading = true
      const res = await getChildDomainListApi(id)
      this.deflist = res.data.list
      this.tableData = res.data.list
      this.loading = false
    },
    // 新增/修改
    submit (val) {
      this.isedit = val
      if (this.domainType !== 'Root') {
        this.dialogForm.parentId = this.domainId
      }
      this.dialogVisible = true
    },

    diaClose () {
      this.dialogVisible = false
      this.dialogForm = {}
    },
    shuaxin () {
      if (!this.domainType) return
      if (this.domainType === '1' || this.domainType === '0') {
        this.getChildDomainList(this.domainId)
        this.refreshNode(this.node.key)
      } else {
        this.getRootDomainList()
        this.refreshNode(this.node.key)
      }
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    // 导出

    // 查询分页信息
    async chaxun () {
      const list = [...this.deflist]
      if (this.inputValue) {
        this.tableData = list.filter((item) =>
          Object.values(item).includes(this.inputValue)
        )
      } else {
        this.tableData = [...list]
      }
    },
    command (val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    refreshNode (key) {
      console.log('key', key)
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      const node = this.$refs.tree.getNode(key)
      console.log('node', node)
      //  设置未进行懒加载状态
      node.loaded = false
      // 重新展开节点就会间接重新触发load达到刷新效果
      this.$nextTick(() => {
        node.expand()
      })
    },
    // 树节点点击
    async handleNodeClick (val, node) {
      console.log(val)
      this.node = node
      console.log('node', this.node)
      this.domainId = val.domainId
      this.domainType = val.domainType
      this.parentId = val.parentId
      this.getChildDomainList(val.domainId)
    },
    // 树组件懒加载
    async loadNode (node, resolve) {
      // if (node.level === 0) {
      //   // 初始的级数（最顶层）
      //   return resolve(this.list) // 最顶层数据渲染为region
      // }
      if (node.level === 0) {
        const res = await getRootDomainListApi()
        return resolve(res?.data.list)
      } else if (node.level > 0) {
        const res = await getChildDomainListApi(node.data.domainId)
        return resolve(res?.data.list)
      } else {
        return resolve([])
      }
    },
    // 树节点过滤
    filterNode (value, data) {
      if (!value) return true
      return data.domainName.indexOf(value) !== -1
    },
    // 新增保存/修改
    async add () {
      await this.$refs.dialogForm.validate()
      if (this.isedit === 'add') {
        if (!this.domainType || this.domainType === 'Root') {
          const res = await addRootDomainApi(this.dialogForm)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
          }
          if (this.node) {
            this.getRootDomainList()
            this.refreshNode(this.node.key)
          }
        } else {
          const res = addChildDomainApi(this.dialogForm)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
          }
          if (this.node) {
            this.$nextTick(() => {
              this.getChildDomainList(this.domainId)
              this.refreshNode(this.node.key)
            })
          }
        }
      } else if (this.isedit === 'edit') {
        const res = await editDomainApi(this.dialogForm)
        console.log(res)
        this.$message({
          type: 'success',
          message: res.message,
          duration: 2000
        })
        if (this.domainType === '1' || this.domainType === '0') {
          this.getChildDomainList(this.domainId)
          this.refreshNode(this.node.key)
        } else {
          this.getRootDomainList()
          this.refreshNode(this.node.key)
        }
      }
      this.diaClose()
    },
    // 移动
    async move (type, item) {
      this.$confirm('此操作将移动模型域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res =
            type === 'up'
              ? await upDomainApi({ domainId: item.domainId })
              : await downDomainApi({ domainId: item.domainId })
          console.log(res)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.message,
              duration: 2000
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message,
              duration: 2000
            })
          }
          if (this.domainType === '1' || this.domainType === '0') {
            this.getChildDomainList(this.domainId)
            this.refreshNode(this.node.key)
          } else {
            this.getRootDomainList()
            this.refreshNode(this.node.key)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消移动',
            duration: 2000
          })
        })
    },
    // 编辑
    async edit (item) {
      this.isedit = 'edit'
      const res = await getDomainDataApi(item.domainId)
      console.log(res)
      const data = res.data.entity
      if (item.domainType === '1') {
        this.dialogForm = {
          domainId: data.domainId,
          parentId: data.parentId,
          domainExplain: data.domainExplain,
          domainCode: data.domainCode,
          domainName: data.domainName
        }
      } else {
        this.dialogForm = {
          domainId: data.domainId,
          domainExplain: data.domainExplain,
          domainCode: data.domainCode,
          domainName: data.domainName
        }
      }
      this.$forceUpdate()
      this.dialogVisible = true
    },
    // 删除
    async del (item) {
      // console.log(id);
      this.$confirm('此操作将永久删除该模型域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delDomainApi(item.domainId)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 2000
              })
              this.chaxun()
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 2000
              })
            }
          } catch (e) {
            console.log(e)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 2000
          })
        })
    },
    chongzhi () {
      this.inputValue = ''
      if (this.domainType === '1' || this.domainType === '0') {
        this.getChildDomainList(this.domainId)
        this.refreshNode(this.node.key)
      } else {
        this.getRootDomainList()
        this.refreshNode(this.node.key)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep textarea {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  background-color: #f1f1f1;
  height: 100%;
  padding: 9px;
  display: flex;
  .leftbox {
    width: 300px;
    height: 100%;
    overflow: auto;
    background-color: #fff;
    padding: 20px;
  }
  .mainbox {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    .top {
      padding: 0 40px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      min-height: 80px;
      background-color: #fff;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 10px;
      align-items: center;
      .search {
        display: flex;
        align-items: center;
        width: 400px;
      }
    }
    .bodybox {
      flex: 1;
      position: relative;
      background-color: #fff;
      padding: 20px;
      padding-bottom: 30px;
      // min-height: 87.6vh;
      .pagination {
        position: absolute;
        right: 20px;
        bottom: 10px;
      }
      .table {
        .titlebox {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          .text {
            font-size: 16px;
          }
          .right {
            align-items: center;
            i {
              margin-left: 10px;
            }
            .bewdao {
              width: 63px;
              height: 32px;
            }
            .daochu {
              background-color: #1890ff;
              color: #fff;
              border: none;
              border-radius: 3px;
            }
          }
        }
      }
      .dialog {
        .title {
          font-size: 28px;
          margin-bottom: 30px;
        }
        .text {
          font-size: 12px;
          color: #3b8eea;
        }
      }
    }
  }
}

::v-deep .el-select {
  width: 100%;
}
::v-deep .el-input {
  height: 32px;
}
::v-deep .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 1;
}
.el-select-dropdown__item {
  padding-left: 10px;
}
::v-deep .el-date-editor {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}
.button {
  width: 63px;
  height: 32px;
  margin-right: 5px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
}
.chaxun {
  background-color: #1890ff;
  color: #fff;
}
::v-deep .el-range-separator {
  line-height: 25px;
}
.timeTitle {
  height: 50px;
}

.dropdown-list {
  padding: 0;
  text-align: center;
  width: 50px;
}

.change-type {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 1);
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.node-img {
  width: 16px;
  height: 16px;
  margin-right: 5px;
  vertical-align: bottom;
}
</style>
